package com.sunmi.usercenter.account;

import java.lang.reflect.Field;
import java.lang.reflect.Type;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.Shop;
import com.sunmi.usercenter.bean.UserLoginInfo;
import com.sunmi.usercenter.bean.rpc.ReqLogin;
import com.sunmi.usercenter.controller.HttpController;
import com.sunmi.usercenter.model.CaCheModel;
import com.sunmi.usercenter.ui.activity.fragment.UserAllInfoFragment;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.ui.component.NetErrorDialog;
import com.sunmi.usercenter.ui.component.NetErrorDialog.TwoToDoOnClickListener;
import com.sunmi.usercenter.utils.MD5Utils;
import com.sunmi.usercenter.utils.NetWorkCenterUtils;

import android.accounts.Account;
import android.accounts.AccountAuthenticatorActivity;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


public class LoginActivity extends AccountAuthenticatorActivity implements OnClickListener,TwoToDoOnClickListener{

	private EditText mEditUsername;
	private EditText mEditPassword;
	private LinearLayout mLinShowPsd;
	private ImageView mImgEye;  
	private TextView mTxtError,mBtnLogin,mTxtForgetPsd,mTxtNewAccount;
	private RelativeLayout mRelBack;
	private boolean isHidden = true;//是否隐藏输入框文本
	private boolean editUsernameIsNull = true,editPasswordIsNull = true;
	private NetErrorDialog netErrorDialog;
	private CaCheModel mCaCheModel;
	private HttpController mHttpController;
	private LoadingDialog mLoadingDialog;
	
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		immerseNotificationBar();
		setContentView(R.layout.fragment_login);

		initView();
//		final Button done = (Button) findViewById(R.id.new_account_done);
//		final EditText server = (EditText) findViewById(R.id.new_account_server);
//		final EditText username = (EditText) findViewById(R.id.new_account_username);
//		final EditText password = (EditText) findViewById(R.id.new_account_password);
//
//		final Activity self = this;
//		done.setOnClickListener(new OnClickListener() {
//			public void onClick(View v) {
//				Account account = new Account(username.getText().toString(),Constant.ACCOUNT_TYPE);
//				Bundle userdata = new Bundle();
//				userdata.putString("SERVER", server.getText().toString());
//				AccountManager mAccountManager = AccountManager.get(self);
//				if (mAccountManager.addAccountExplicitly(account, password.getText().toString(), userdata)) {
//					Bundle result = new Bundle();
//					result.putString(AccountManager.KEY_ACCOUNT_NAME, username.getText().toString());
//					result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constant.ACCOUNT_TYPE);
//					setAccountAuthenticatorResult(result);
//				}
//				finish();
//			}
//		});
	}
	
	
	
	@SuppressLint({ "InlinedApi", "NewApi" })
	private void immerseNotificationBar(){
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
	}
	
	@SuppressLint("NewApi")
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		this.findViewById(R.id.layout).setPadding(0, getStatusBarHeight(getApplicationContext()), 0, 0);
	}
	
	/** 得到通知栏高度 */
	public int getStatusBarHeight(Context context) {
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0, statusBarHeight = 0;
		try {
			c = Class.forName("com.android.internal.R$dimen");
			obj = c.newInstance();
			field = c.getField("status_bar_height");
			x = Integer.parseInt(field.get(obj).toString());
			statusBarHeight = context.getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return statusBarHeight;
	}
	
	/**
	 * 是否显示文本框的内容
	 */
	private void showPsdOrHidePsd(){
		if(isHidden){
			mEditPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
			mImgEye.setBackgroundResource(R.drawable.eye_yes);
		}else{
			mEditPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
			mImgEye.setBackgroundResource(R.drawable.eye_no);
		}
		isHidden = !isHidden;
		mEditPassword.postInvalidate();
		//切换后将EditText光标置于末尾
        CharSequence charSequence = mEditPassword.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
	}
	
	private void login(){
		if(!NetWorkCenterUtils.isNetworkConnected(getApplicationContext())){
			netErrorDialog = NetErrorDialog.createDialog(getApplicationContext(), this);
			netErrorDialog.show();
		}
		mLoadingDialog = LoadingDialog.createDialog(this, getString(R.string.logining));
		mLoadingDialog.show();
		final String username = mEditUsername.getText().toString().trim();
		final String password = mEditPassword.getText().toString();
		ReqLogin reqLogin = new ReqLogin();
		reqLogin.setPassword(MD5Utils.md5Password(username, password));
		reqLogin.setUserName(username);
		mHttpController.login(reqLogin, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				String json = new String(arg2);
				Gson gson = new Gson();
				Type type = new TypeToken<Result<Shop>>(){}.getType();
				Result<Shop> result = null;
				try {
					result = gson.fromJson(json,type);
				}catch (Exception e){
					e.printStackTrace();
				}
				if(result!=null&&result.getCode()==1){
//					showToast("登录成功！");
					Toast.makeText(getApplicationContext(), getString(R.string.login_success), Toast.LENGTH_SHORT).show();
					if(result.data!=null){
						mCaCheModel.saveShop(result.data);
					}
					UserLoginInfo userLoginInfo = new UserLoginInfo();
					userLoginInfo.setPassword(password);
					userLoginInfo.setUsername(username);
//					mCaCheModel.saveUserPasswordAndUsername(userLoginInfo);
					
					Account account = new Account(username,Constant.ACCOUNT_TYPE);
					Bundle userdata = new Bundle();
					userdata.putString("SERVER", "sunmi.com");
					AccountManager mAccountManager = AccountManager.get(getApplicationContext());
					if (mAccountManager.addAccountExplicitly(account, password, userdata)) {
						Bundle bundle = new Bundle();
						bundle.putString(AccountManager.KEY_ACCOUNT_NAME, username);
						bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, Constant.ACCOUNT_TYPE);
						setAccountAuthenticatorResult(bundle);
					}
					LoginActivity.this.finish();
					
//					openFM(new FmInfo(UserAllInfoFragment.class, null));
				}else{
					mTxtError.setVisibility(View.VISIBLE);
				}
				mLoadingDialog.dismiss();
			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				mLoadingDialog.dismiss();
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
//			openFM(new FmInfo(StartRegisterFragment.class, null));
			break;
		case R.id.ln_show_psd:
			showPsdOrHidePsd();
			break;
		case R.id.btn_login:
			login();
			break;
		case R.id.txt_forget_pad:
//			openFM(new FmInfo(RetrievePsdFragment.class, null));
			break;
		case R.id.txt_new_account:
//			openFM(new FmInfo(RegisterFragment.class, null));
			break;
		default:
			break;
		}
	}
	
	private void editChangeListenter(){
		mEditPassword.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				editPasswordIsNull = s.length()==0;
				changeLoginBtn();
			}
		});
		mEditUsername.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			@Override
			public void afterTextChanged(Editable s) {
				editUsernameIsNull = s.length()==0;
				changeLoginBtn();
			}
		});
	}
	
	private void changeLoginBtn(){
		if(!editPasswordIsNull&&!editUsernameIsNull){
			mBtnLogin.setBackgroundResource(R.drawable.btn_bg);
			mBtnLogin.setEnabled(true);
		}else{
			mBtnLogin.setBackgroundResource(R.drawable.btn_bg_no_click2);
			mBtnLogin.setEnabled(false);
		}
	}

	@Override
	public void changNet() {
		    	Intent intent = new Intent();
		    	intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
		    	startActivity(intent);
	}

	@Override
	public void ok() {
		netErrorDialog.dismiss();
	}
	
	/**
	 * 初始化
	 */
	private void initView(){
//		SetStatusColorf5f5f5();
		mHttpController = HttpController.getInstance(getApplicationContext());
		mCaCheModel = CaCheModel.getInstance(getApplicationContext());
		mEditUsername = (EditText) this.findViewById(R.id.txt_username);
		mEditPassword = (EditText) this.findViewById(R.id.txt_password);
		mRelBack = (RelativeLayout) this.findViewById(R.id.back);
		mLinShowPsd = (LinearLayout) this.findViewById(R.id.ln_show_psd);
		mImgEye = (ImageView) this.findViewById(R.id.img_eye);
		mTxtError = (TextView) this.findViewById(R.id.txt_error);
		mBtnLogin = (TextView) this.findViewById(R.id.btn_login);
		mTxtForgetPsd = (TextView) this.findViewById(R.id.txt_forget_pad);
		mTxtNewAccount = (TextView) this.findViewById(R.id.txt_new_account);
		findViewById(R.id.line2).setVisibility(View.INVISIBLE);
		mRelBack.setOnClickListener(this);
		mLinShowPsd.setOnClickListener(this);
		mBtnLogin.setOnClickListener(this);
		mTxtForgetPsd.setOnClickListener(this);
		mTxtNewAccount.setOnClickListener(this);
		mBtnLogin.setBackgroundResource(R.drawable.btn_bg_no_click2);
		mBtnLogin.setEnabled(false);
		mRelBack.setVisibility(View.INVISIBLE);
		mTxtForgetPsd.setVisibility(View.INVISIBLE);
		mTxtNewAccount.setVisibility(View.INVISIBLE);
//		UserLoginInfo info = mCaCheModel.readUserPasswordAndUsername();
//		if(info!=null){
//			if(info.getUsername().length()>0){
//				mEditUsername.setText(info.getUsername());
//				editUsernameIsNull = false;
//			}
//			if(info.getPassword().length()>0){
//				mEditPassword.setText(info.getPassword());
//				editPasswordIsNull = false;
//			}
//			changeLoginBtn();
//		}
		editChangeListenter();
	}
	

}
